package controller;

import io.javalin.http.Context;
import service.PlaylistService;
import util.JwtUtil;
import util.ResponseUtil;
import util.ValidationUtil;
import java.util.*;

public class PlaylistController {
    private static final PlaylistService playlistService = new PlaylistService();
    
    // 获取歌单基本信息（不需要登录）
    public static void getPlaylistInfo(Context ctx) {
        try {
            String playlistId = ctx.pathParam("id");
            
            // 尝试获取登录用户ID（可选）
            Long currentUserId = null;
            String token = ctx.header("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                try {
                    token = token.substring(7);
                    if (JwtUtil.validateToken(token)) {
                        currentUserId = JwtUtil.getUserIdFromToken(token);
                    }
                } catch (Exception ignored) {}
            }
            
            ctx.json(playlistService.getPlaylistInfo(playlistId, currentUserId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取歌单信息失败"));
        }
    }
    
    // 获取完整歌单（不需要登录）
    public static void getFullPlaylist(Context ctx) {
        try {
            String playlistId = ctx.pathParam("id");
            List<Map<String, Object>> songs = playlistService.getFullPlaylist(playlistId);
            ctx.json(ResponseUtil.success(songs));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取歌单歌曲失败"));
        }
    }
    
    // 获取用户创建的所有歌单（需要登录）
    public static void getUserPlaylists(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            ctx.json(playlistService.getUserPlaylists(userId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取用户歌单失败"));
        }
    }
    
    // 获取用户收藏的所有歌单（需要登录）
    public static void getFavoritePlaylists(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            ctx.json(playlistService.getFavoritePlaylists(userId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取收藏歌单失败"));
        }
    }
    
    // 创建歌单
    public static void createPlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String name = ctx.formParam("name");
            String description = ctx.formParam("description");
            
            ValidationUtil.validatePlaylistName(name);
            ValidationUtil.validatePlaylistDescription(description);
            
            ctx.json(playlistService.createPlaylist(
                userId,
                name,
                description,
                ctx.uploadedFile("cover")
            ));
            
        } catch (IllegalArgumentException e) {
            ctx.json(ResponseUtil.error(e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("创建歌单失败"));
        }
    }
    
    // 删除歌单
    public static void deletePlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            
            ctx.json(playlistService.deletePlaylist(userId, playlistId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("删除歌单失败"));
        }
    }
    
    // 收藏/取消收藏歌单
    public static void favoritePlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            
            ctx.json(playlistService.toggleFavorite(userId, playlistId, true));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("收藏歌单失败"));
        }
    }
    
    public static void unfavoritePlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            
            ctx.json(playlistService.toggleFavorite(userId, playlistId, false));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("取消收藏失败"));
        }
    }
    
    // 获取热门歌单
    public static void getHotPlaylists(Context ctx) {
        try {
            int limit = ctx.queryParamAsClass("limit", Integer.class).getOrDefault(10);
            
            // 获取当前登录用户ID（如果有的话）
            Long currentUserId = null;
            String token = ctx.header("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                try {
                    token = token.substring(7);
                    if (JwtUtil.validateToken(token)) {
                        currentUserId = JwtUtil.getUserIdFromToken(token);
                    }
                } catch (Exception ignored) {}
            }
            
            ctx.json(playlistService.getHotPlaylists(limit, currentUserId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("获取热门歌单失败"));
        }
    }
    
    // 修改歌单信息
    public static void updatePlaylistName(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            String newName = ctx.bodyAsClass(Map.class).get("name").toString();
            
            ValidationUtil.validatePlaylistName(newName);
            ctx.json(playlistService.updatePlaylistInfo(userId, playlistId, newName, null, null));
            
        } catch (IllegalArgumentException e) {
            ctx.json(ResponseUtil.error(e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("修改歌单名称失败"));
        }
    }
    
    public static void updatePlaylistDescription(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            String newDescription = ctx.bodyAsClass(Map.class).get("description").toString();
            
            ValidationUtil.validatePlaylistDescription(newDescription);
            ctx.json(playlistService.updatePlaylistInfo(userId, playlistId, null, newDescription, null));
            
        } catch (IllegalArgumentException e) {
            ctx.json(ResponseUtil.error(e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("修改歌单描述失败"));
        }
    }
    
    public static void updatePlaylistCover(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            
            ctx.json(playlistService.updatePlaylistInfo(userId, playlistId, null, null, ctx.uploadedFile("cover")));
            
        } catch (IllegalArgumentException e) {
            ctx.json(ResponseUtil.error(e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("修改歌单封面失败"));
        }
    }
    
    // 歌单歌曲管理
    public static void addSongsToPlaylists(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            Map<String, Object> body = ctx.bodyAsClass(Map.class);
            List<String> songIds = (List<String>) body.get("songIds");
            List<String> playlistIds = (List<String>) body.get("playListIds");
            
            ctx.json(playlistService.addSongsToPlaylists(userId, songIds, playlistIds));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("添加歌曲到歌单失败"));
        }
    }
    
    public static void removeSongsFromPlaylist(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            List<String> songIds = (List<String>) ctx.bodyAsClass(Map.class).get("songIds");
            
            ctx.json(playlistService.removeSongsFromPlaylist(userId, playlistId, songIds));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("删除歌曲失败"));
        }
    }
    
    // 将歌单添加到播放队列
    public static void addPlaylistToQueue(Context ctx) {
        try {
            String token = ctx.header("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                ctx.json(ResponseUtil.unauthorized());
                return;
            }
            
            Long userId = JwtUtil.getUserIdFromToken(token.substring(7));
            String playlistId = ctx.pathParam("id");
            
            ctx.json(playlistService.addPlaylistToQueue(userId, playlistId));
            
        } catch (Exception e) {
            e.printStackTrace();
            ctx.json(ResponseUtil.error("添加歌单到播放列表失败"));
        }
    }
}